<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\Post\Post as PostModel;
use app\common\model\Post\Comment as CommentModel;
use app\common\model\User\User as UserModel;
use app\common\model\User\Record as RecordModel;
use app\common\validate\Post\Comment as CommentValidate;
use app\home\middleware\Auth;
use think\exception\ValidateException;

class Comment extends BaseController
{
    // 控制器中间件
    protected $middleware = [
        Auth::class
    ];
    protected function initialize()
    {
        parent::initialize();

        $this->CommentModel = new CommentModel();
        $this->PostModel = new PostModel();
        $this->UserModel = new UserModel();
        $this->RecordModel = new RecordModel();
    }

    public function add()
    {
        if($this->request->param())
        {
            // 接收帖子id
            $postid = $this->request->param('postid',0);

            $post = PostModel::find($postid);

            if(!$post)
            {
                $this->error('帖子已删除，请重新选择');
            }

            // 评论上一级id
            $pid = $this->request->param('pid',0);
            // 评论内容
            $content = $this->request->param('content','');

            // 去掉where条件 查询评论表是否该条评论
            $comment = CommentModel::find($pid);

            if($comment)
            {
                // 评论等级字段 需要+1
                $level = $comment['level'] + 1;
                
            }else{
                // 设置为0
                $level = 0;
                
            }

            // 封装数据
            $data = [
                'pid' => $pid,
                'content' => $content,
                'level' => $level,
                'userid' => $this->request->LoginUser['id'],
                'postid' => $postid,
                'accept' => 0
            ];

            try {
                validate(CommentValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }

            $result = $this->CommentModel->save($data);

            if($result !== true)
            {
                $this->error($this->CommentModel->getError());
            }else{
                $this->success('评论成功',(String)url("home/index/info",['postid' => $postid]));
            }

        }
    }

    public function like()
    {
        if ($this->request->isAjax())
        {
            // 接收点赞的评论
            $comid = $this->request->param('comid', 0);

            // 查询那条评论
            $Comment = $this->CommentModel->find($comid);

            // 是否存在
            if(!$Comment)
            {
                $this->error('该评论无法点赞');
            }

            // 获取已经点赞id 并且转数组
            $LikeArr = !empty($Comment['like']) ? array_filter(explode(',', $Comment['like'])) : [];

            // 现在登录用户
            $userid = $this->request->LoginUser['id'];

            // 判断该用户是否点赞了
            if(!in_array($userid,$LikeArr))
            {
                // 如果不存在数组里就追加数组里
                $LikeArr[] = $userid;

                // 封装数组
                $LikeData = [
                    'like' => implode(',', $LikeArr),
                ];

                // 更新数据
                $result = $Comment->save($LikeData);

                if($result !== true)
                {
                    $this->error('该评论失败，请重新点赞');

                }else{
                    $this->success('点赞成功');

                }

            }else{
                foreach($LikeArr as $key => $item)
                {
                    if($item == $userid)
                    {
                       unset($LikeArr[$key]);
                       break;
                    }
                }

                // 封装数组
                $LikeData = [
                    'like' => implode(',', $LikeArr),
                ];

                // halt($LikeData);
                // 更新数据
                $result = $Comment->save($LikeData);

                if($result !== true)
                {
                    $this->error('该评论无法取消点赞');

                }else{
                    $this->success('取消点赞了');

                }
            }
            
        }
    }

    public function accept()
    {
        if($this->request->isAjax())
        {
            // 获取评论id
            $comid = $this->request->param('comid',0);

            $Comment = $this->CommentModel->withJoin(['user','post'],'LEFT')->find($comid);

            if(!$Comment)
            {
                $this->error('评论已删除，无法采纳');
            }

            if($Comment['accept'] == 1 || $Comment['post']['accept'])
            {
                $this->error('评论已被采纳');
            }

            // 评论表 accept 0 = 1
            // 帖子表 accept null = userid => 该条评论的用户
            // 用户表 point 更新 => 被采纳用户的积分
            // 用户消费记录表 新增记录

            // 开启事务
            $this->PostModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CommentModel->startTrans();

            // 更新评论采纳状态
            $AcceptData = [
                'accept' => 1
            ];


            // 更新
            $CommentStatus = $Comment->save($AcceptData);

            if($CommentStatus !== true)
            {
                $this->error($Comment->getError());
            }

            // 更新帖子的采纳id
            $PostData = [
                'accept' => $Comment['userid']
            ];

            // 查询
            $Post = PostModel::find($Comment['postid']);

            // 更新
            $PostResult = $Post->save($PostData);

            if($PostResult !== true)
            {
                $Comment->rollback();
                $this->error($Post->getError());
            }

            // 用户积分
            $UserPoint = $Comment['user']['point'];
            // 帖子悬赏积分
            $PostPoint = $Comment['post']['point'];

            $Point = bcadd((String)$UserPoint,(String)$PostPoint);

            // 更新用户的积分
            $UserData = [
                'point' => $Point
            ];

            $User = UserModel::find($Comment['userid']);
            // 更新
            $UserResult = $User->save($UserData);

            if($UserResult !== true)
            {
                $this->CommentModel->rollback();
                $this->PostModel->rollback();
                $this->error($User->getError());
            }

            // RecordModel
            $RecordData = [
                'point' => $PostPoint,
                'content' => "您的【".$Comment['content']."】评论被采纳了，获取".$PostPoint."积分",
                'state' => 2,
                'userid' => $Comment['userid']
            ];

            // 更新
            $RecordResult = $this->RecordModel->save($RecordData);

            if($RecordResult !== true)
            {
                $this->CommentModel->rollback();
                $this->PostModel->rollback();
                $this->UserModel->rollback();
                $this->error($this->RecordModel->getError());
            }


            // 最终判断
            if($RecordResult !== true || $UserResult !== true || $PostResult !== true || $CommentStatus !== true)
            {
                $this->CommentModel->rollback();
                $this->PostModel->rollback();
                $this->UserModel->rollback();
                $this->RecordModel->rollback();
                $this->error('采纳失败，请重新选择');
            }else{
                $this->CommentModel->commit();
                $this->PostModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->success('采纳成功');
            }

        }
    }

    public function del()
    {
        if($this->request->isAjax())
        {
            $comid = $this->request->param('comid',0,'trim');

            $Comment = CommentModel::find($comid);

            if(!$Comment)
            {
                $this->error('该评论不存在，无法删除');
            }
            
            // 查询查询该评论是否是父级评论
            $CommentList = CommentModel::select();

            // 根据评论父级id递归处理相应数据
            $CommentData = getSubTree($CommentList,$comid);

            // 存放评论id的数据
            $IdArr = [];

            // 循环
            foreach($CommentData as $item)
            {
                // 把循环出来的id放一起
                $IdArr[] = $item['id'];
            }

            // 追加id并且放在该数组里第一位
            array_unshift($IdArr,$Comment['id']);

            // 删除
            $result = CommentModel::destroy($IdArr);

            if($result !== true)
            {
                $this->error('删除评论失败');
            }else{
                $this->success('删除评论成功');
            }

            
        }
    }
}
